package com.systop.tea.controller;

import com.systop.tea.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    private String imgDirPath;

    public CommonController() {
        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            File imgDir = new File(new File(path).getAbsolutePath(), "images");
            this.imgDirPath = imgDir.getPath();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        // System.out.println("上传路径------>" + imgDirPath + File.separator + fileName);

        try {
            file.transferTo(new File(imgDirPath + File.separator + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) {
        try {
            // ClassPathResource classPathResource = new ClassPathResource("images" + File.separator + fileName);
            // InputStream fileInputStream = classPathResource.getInputStream();
            FileInputStream fileInputStream = new FileInputStream(imgDirPath + File.separator + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            // System.out.println("下载路径------>" + classPathResource.getPath());

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes);
                outputStream.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
